/*=====================================================================

  File:      Utilities.cs
  Summary:   SQL Remote Blob Storage sample provider. Support file for 
             a provider that uses NTFS files as the blob store.
             Class containing various utility functions.
  Date:	     June 24th, 2008

---------------------------------------------------------------------

  This file is part of the Microsoft SQL Server Code Samples.
  Copyright (C) Microsoft Corporation.  All rights reserved.

This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation.  See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.

======================================================= */

using System;
using System.IO;

namespace Microsoft.Data.BlobStores.FileBlobStore
{
    /// <summary>
    /// Utility functions
    /// </summary>
    internal
    sealed
    class Utilities
    {
        private Utilities() { }

        /// <summary>
        /// Outputs data from a read stream to a newly created file
        /// </summary>
        internal
        static
        void WriteStreamToFile(Stream readStream, string path)
        {
            using (FileStream writeStream = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                Utilities.ReadWriteStream(readStream, writeStream);
            }
        }

        /// <summary>
        /// Outputs data from a read stream to a write stream
        /// </summary>
        internal
        static
        void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            if (readStream == null) throw new ArgumentNullException("readStream");
            if (writeStream == null) throw new ArgumentNullException("writeStream");

            int bufferLength = 256;
            Byte[] buffer = new Byte[bufferLength];
            int bytesRead = readStream.Read(buffer, 0, bufferLength);

            // Write out the input stream
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, bufferLength);
            }
        }
    }
}

